package au.com.somethingwritten.controller;

import au.com.somethingwritten.model.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class SearchController extends HttpServlet {
	

	public void doPost( HttpServletRequest request,
						HttpServletResponse response)
						throws IOException, ServletException {
		
		//get the requested search type.
		String searchOption = (String)request.getParameter("search_options");
		//if the option is unspecified, set it to default
		if(searchOption == null)
			searchOption = "all";
		//get the requested search term(s).
		String searchText = request.getParameter("search_text");
		if(searchText == null)
			searchText = "";
		
		//Create a book manager
		BookManager bookMan = new BookManager();
		//get all books in database
		ArrayList<Book> results = new ArrayList<Book>();
		
		if(searchOption.contains("authors")){
			//search by author
			results = bookMan.findBooksByAuthor(searchText);
		}else if(searchOption.contains("categories")){
			//search by category
			results = bookMan.findBooksByCategory(searchText);
		}else if(searchOption.contains("titles")){
			//search by titles.
			results = bookMan.findBooksByTitle(searchText);
		}else if(searchOption.contains("isbn")){
			//search by isbn.
			results = bookMan.findBooksByISBN(searchText);
		}else{
			//default: search by everything.
			results = bookMan.findBooks(searchText);
		}
		
		//store books in the request
		request.setAttribute("books", results);
		//forward data to the view
		RequestDispatcher view = request.getRequestDispatcher("resultsPage.jsp");
		view.forward(request, response);
	}
	
	public void doGet( HttpServletRequest request,
			HttpServletResponse response)
			throws IOException, ServletException {
			//handle gets as posts.
			doPost(request, response); 
	}
}
